<template>
  <div class="activity-notification">
    <div class="container">
      <header class="page-header">
        <h1 class="page-title">我的活动消息</h1>
        <div class="header-actions">
          <el-button
            type="danger"
            size="small"
            :disabled="selectedIds.length === 0"
            @click="handleBatchDelete"
            :loading="loading"
            class="batch-delete-btn"
          >
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
        </div>
      </header>

      <div class="notification-wrapper">
        <div class="selection-bar">
          <el-checkbox
            :model-value="isAllSelected"
            :indeterminate="isIndeterminate"
            @change="handleSelectAll"
            class="select-all"
          >
            全选
          </el-checkbox>

          <div class="filter-options">
            <el-radio-group
              v-model="filterParams.readStatus"
              @change="handleFilterChange"
              class="filter-group"
            >
              <el-radio-button value="">全部</el-radio-button>
              <el-radio-button value="0">未读</el-radio-button>
              <el-radio-button value="1">已读</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <div v-if="messages.length > 0" class="notification-list">
          <div
            v-for="item in messages"
            :key="item.id"
            class="notification-card"
            :class="{
              'is-new': item.readStatus === 0,
              'is-selected': selectedIds.includes(item.id),
            }"
            @click="markAsRead(item)"
          >
            <div class="card-checkbox">
              <el-checkbox
                :model-value="selectedIds.includes(item.id)"
                @change="(val) => handleSelectItem(val, item.id)"
                @click.stop
              ></el-checkbox>
            </div>
            <img :src="item.cover || '/assets/activity-placeholder.jpg'" class="activity-img" />
            <div class="card-content">
              <div class="card-header">
                <h3 class="card-title">{{ item.title }}</h3>
                <span class="message-time">
                  <el-icon><Calendar /></el-icon>
                  {{ item.startTime }}
                </span>
              </div>
              <div class="card-info-item">
                <el-icon><Document /></el-icon>
                <div class="info-content">
                  <div class="info-label">通知内容</div>
                  <p class="card-description">{{ item.content }}</p>
                </div>
              </div>
              <div class="card-info-item">
                <el-icon><Location /></el-icon>
                <div class="info-content">
                  <div class="info-label">活动举办位置</div>
                  <p class="card-description">{{ item.detailAddress }}</p>
                </div>
              </div>
              <div class="card-info-grid">
                <div class="card-info-item compact">
                  <el-icon><User /></el-icon>
                  <div class="info-content">
                    <div class="info-label">举办人</div>
                    <p class="card-description">{{ item.holdName }}</p>
                  </div>
                </div>
                <div class="card-info-item compact">
                  <el-icon><Phone /></el-icon>
                  <div class="info-content">
                    <div class="info-label">联系电话</div>
                    <p class="card-description">{{ item.holdPhone }}</p>
                  </div>
                </div>
              </div>
              <div class="card-meta">
                <span
                  class="meta-tag status"
                  :class="item.readStatus === 0 ? 'unread' : 'read'"
                >
                  <el-icon>
                    <Document v-if="item.readStatus === 0" />
                    <Check v-else />
                  </el-icon>
                  {{ item.readStatus === 0 ? "未读" : "已读" }}
                </span>
              </div>
            </div>

            <div class="card-actions">
              <el-button
                v-if="item.activityId"
                type="primary"
                class="view-details-btn"
                @click.stop="viewActivityDetails(item.activityId)"
              >
                查看活动
                <el-icon class="el-icon--right"><ArrowRight /></el-icon>
              </el-button>

              <el-button
                type="danger"
                plain
                class="delete-btn"
                @click.stop="handleDelete(item.id)"
                :loading="loading"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <div class="empty-content">
            <el-icon class="empty-icon"><Document /></el-icon>
            <p>暂无活动消息</p>
            <el-button type="primary" @click="$router.push('/index')">浏览活动</el-button>
          </div>
        </div>

        <div class="pagination-wrapper">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.size"
            :current-page="pagination.page"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  activityNotificationPage,
  activityNotificationDeleteById,
  activityNotificationDeleteBatch,
  activityNotificationEdit,
} from "@/apis/user/activity-notification";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Check,
  User,
  Phone,
  Location,
  Document,
  ArrowRight,
  Calendar,
  Timer,
} from "@element-plus/icons-vue";
// 路由
const router = useRouter();

// 数据状态
const messages = ref([]);
const selectedIds = ref([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  page: 1,
  size: 5,
  total: 0,
});

// 筛选和排序参数
const searchParams = reactive({
  userId: "",
});

const filterParams = ref({
  readStatus: "", // 空字符串表示全部，0表示未读，1表示已读
});

const orderParams = reactive({
});

// 计算属性 - 全选状态
const isAllSelected = computed(() => {
  return (
    messages.value.length > 0 &&
    selectedIds.value.length === messages.value.length
  );
});

// 计算属性 - 部分选中状态
const isIndeterminate = computed(() => {
  return (
    selectedIds.value.length > 0 &&
    selectedIds.value.length < messages.value.length
  );
});

// 获取消息列表数据
const fetchMessages = async () => {
  try {
    loading.value = true;
    const response = await activityNotificationPage(
      {
        filter: filterParams.value,
        search: searchParams,
        orders: [orderParams],
      },
      pagination.page,
      pagination.size
    );

    if (response && response.data) {
      messages.value = response.data.records;
      pagination.total = response.data.total;
    }
  } catch (error) {
    console.error("获取活动消息失败:", error);
    ElMessage.error("获取活动消息失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 筛选变化处理
const handleFilterChange = () => {
  pagination.page = 1; // 重置到第一页
  fetchMessages();
};

// 分页变化处理
const handlePageChange = (page) => {
  pagination.page = page;
  fetchMessages();
};

// 每页条数变化处理
const handleSizeChange = (size) => {
  pagination.size = size;
  pagination.page = 1; // 重置到第一页
  fetchMessages();
};

// 标记消息为已读
const markAsRead = async (item) => {
  try {
    const id = item.id;
    const message = messages.value.find((item) => item.id === id);
    if (message && message.readStatus === 0) {
      item.readStatus = 1;
      await activityNotificationEdit(item);

      // 更新本地状态
      const index = messages.value.findIndex((item) => item.id === id);
      if (index !== -1) {
        messages.value[index].readStatus = 1;
      }
    }
  } catch (error) {
    console.error("标记消息已读失败:", error);
  }
};

// 选择/取消选择单个消息
const handleSelectItem = (selected, itemId) => {
  if (selected) {
    selectedIds.value.push(itemId);
  } else {
    const index = selectedIds.value.indexOf(itemId);
    if (index !== -1) {
      selectedIds.value.splice(index, 1);
    }
  }
};

// 全选/取消全选
const handleSelectAll = (selected) => {
  if (selected) {
    selectedIds.value = messages.value.map((item) => item.id);
  } else {
    selectedIds.value = [];
  }
};

// 删除单条消息
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm("确定要删除这条消息吗？", "删除提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    loading.value = true;
    const response = await activityNotificationDeleteById(id);

    if (response && response.code === "00000") {
      ElMessage.success("删除成功");

      // 如果删除的是已选中的项，从选中列表中移除
      const index = selectedIds.value.indexOf(id);
      if (index !== -1) {
        selectedIds.value.splice(index, 1);
      }

      fetchMessages(); // 刷新列表
    } else {
      ElMessage.error(response?.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除消息失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要删除的消息");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条消息吗？`,
      "批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const response = await activityNotificationDeleteBatch(selectedIds.value);

    if (response && response.code === "00000") {
      ElMessage.success("批量删除成功");
      selectedIds.value = []; // 清空选中列表
      fetchMessages(); // 刷新列表
    } else {
      ElMessage.error(response?.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除消息失败:", error);
      ElMessage.error("批量删除失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

// 查看活动详情
const viewActivityDetails = (activityId) => {
  router.push({
    name: "activityDetail",
    params: { activityId },
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchMessages();
});
</script>

<style scoped>
.activity-notification {
  padding: 24px;
  min-height: 100vh;
  background-color: #f8f9fb;
  font-family: 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  position: relative;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: -16px;
  left: 0;
  width: 40px;
  height: 3px;
  background-color: #409eff;
  border-radius: 3px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.batch-delete-btn {
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(245, 34, 45, 0.15);
  transition: all 0.3s;
}

.selection-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.filter-options {
  display: flex;
  align-items: center;
}

.filter-group {
  margin-left: 8px;
}

.notification-wrapper {
  background-color: transparent;
  border-radius: 8px;
}

.notification-list {
  margin-bottom: 24px;
}

.notification-card {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.notification-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.notification-card.is-new {
  position: relative;
}

.notification-card.is-new::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background-color: #409eff;
}

.notification-card.is-selected {
  border: 1px solid #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.card-checkbox {
  display: flex;
  align-items: center;
  padding: 0 12px;
}

.activity-img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin: 16px 0 16px 0;
}

.card-content {
  flex: 1;
  padding: 16px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.message-time {
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.message-time .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

.card-info-item {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.card-info-item .el-icon {
  color: #909399;
  font-size: 16px;
  margin-right: 8px;
  margin-top: 2px;
}

.info-content {
  flex: 1;
  overflow: hidden;
}

.info-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
  font-weight: 500;
}

.card-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
}

.card-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 12px;
}

.card-info-item.compact {
  margin-bottom: 0;
}

.card-meta {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.meta-tag {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 8px;
}

.meta-tag.status {
  color: #fff;
}

.meta-tag.status.unread {
  background-color: #409eff;
}

.meta-tag.status.read {
  background-color: #67c23a;
}

.meta-tag .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.card-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 16px;
  border-left: 1px solid #ebeef5;
  background-color: #fafafa;
}

.view-details-btn,
.delete-btn {
  margin-left: 10px;
  margin-bottom: 12px;
  border-radius: 4px;
  width: 110px;
}

.view-details-btn {
  background-color: #409eff;
  border-color: #409eff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
}

.view-details-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.delete-btn {
  margin-bottom: 0;
}

.el-icon--right {
  margin-left: 5px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 64px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.empty-content {
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.empty-content p {
  color: #909399;
  font-size: 16px;
  margin-bottom: 24px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

@media (max-width: 768px) {
  .activity-notification {
    padding: 16px;
  }
  
  .notification-card {
    flex-direction: column;
  }
  
  .card-checkbox {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 1;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    padding: 4px;
  }
  
  .activity-img {
    width: 100%;
    height: 180px;
    margin: 0;
    border-radius: 8px 8px 0 0;
  }
  
  .card-actions {
    flex-direction: row;
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding: 12px 16px;
    justify-content: flex-end;
  }
  
  .view-details-btn,
  .delete-btn {
    margin-bottom: 0;
    margin-left: 12px;
  }
  
  .card-info-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}
</style>